package com.yourbatis;

import com.yourbatis.interpreter.Interpreter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLTree {
    private List<XMLTree> son = new ArrayList<>();
    private XMLTagType title;
    private StringBuffer text = new StringBuffer();
    private Map<AttributeType, String>  attributes = new HashMap();




    public String exec(Map<String, Object> map){
        String val = getText().toString();
        val += lookup(son, map);
        return val;
    }

    public  String lookup(List<XMLTree> nodes, Map<String, Object> map){
        String val = "";
        for (XMLTree xmlTree : nodes) {
            if (XMLTagType.WHERE.equals(xmlTree.getTitle())){
                val += "where ";
            }
            if (xmlTree.getTitle() == null){
                val += xmlTree.getText() + " ";
            }

            if(XMLTagType.IF.equals(xmlTree.getTitle())){
                Object interpret = Interpreter.interpret(xmlTree.getAttribute(AttributeType.TEST), map);
                if((interpret instanceof Boolean && (Boolean) interpret) || interpret.equals("true")){
                    val += xmlTree.exec(map);
                }
            }
        }
        return val;
    }

    public XMLTree getParent() {
        return parent;
    }

    public void setParent(XMLTree parent) {
        this.parent = parent;
    }

    private XMLTree parent;


    public XMLTagType getTitle() {
        return title;
    }

    public void setTitle(XMLTagType title) {
        this.title = title;
    }

    public List<XMLTree> getSon() {
        return son;
    }

    public void setSon(List<XMLTree> son) {
        this.son = son;
    }

    public StringBuffer getText() {
        return text;
    }

    public void setText(StringBuffer text) {
        this.text = text;
    }

    public Map<AttributeType, String> getAttributes() {
        return attributes;
    }

    public String getAttribute(AttributeType key) {
        return attributes.get(key);
    }

    public void setAttributes(Map<AttributeType, String> attributes) {
        this.attributes = attributes;
    }

    public void putAttributes(String key, String value) {
        this.attributes.put(AttributeType.of(key), value);
    }

    @Override
    public String toString() {
        return "XMLTree{" +
                "son=" + son +
                ", title=" + title +
                ", text=" + text +
                ", attributes=" + attributes +
                ", parent=" + parent +
                '}';
    }

    public void addChild(XMLTree xmlTree){
        this.son.add(xmlTree);
    }
}
